import { Component, OnInit, Injector, TemplateRef } from '@angular/core';
import { NzFormatEmitEvent, NzTreeNode, NzDropdownMenuComponent, NzContextMenuService } from 'ng-zorro-antd';
import { AppComponentBase } from '@shared/component-base/app-component-base';
import { UserServiceProxy, RoleServiceProxy } from '@shared/service-proxies/service-proxies';
import { OrganizationUnitsServiceProxy } from 'services/organizationunits/organizationunits.service';
import { CreateOrUpdateOrganizationUnitsComponent } from './create-or-update-organizationunits/create-or-update-organizationunits.component';
import { PagedResultDto } from '@shared/component-base';
import { AddUsersComponent } from './add-users/add-users.component';
import { AddRolesComponent } from './add-roles/add-roles.component';

@Component({
    selector: 'app-organizationunits',
    templateUrl: './organizationunits.component.html',
    styleUrls: ['./organizationunits.component.scss'],
    providers: [UserServiceProxy, RoleServiceProxy, OrganizationUnitsServiceProxy]
})
export class OrganizationUnitsComponent extends AppComponentBase implements OnInit {
    constructor(injector: Injector, private organizationunitsService: OrganizationUnitsServiceProxy, private nzContextMenuService: NzContextMenuService) {
        super(injector);
    }
    configDing = [
        { value: 1, text: '组织成员', selected: true },
        { value: 2, text: '角色', selected: false },
    ]

    activedNode: NzTreeNode;
    nodes = [];
    loading = false;
    tempNode: string;
    cardTitle = "请选择左侧节点";
    //以下变量用于用户角色的查询和界面渲染
    unitUsersList: any[] = [];
    unitRolesList: any[] = [];
    queryUser: any = {
        pageIndex: 1,
        pageSize: 10,
        skipCount: function () { return (this.pageIndex - 1) * this.pageSize; },
        total: 0,
    };
    queryRole: any = {
        pageIndex: 1,
        pageSize: 10,
        skipCount: function () { return (this.pageIndex - 1) * this.pageSize; },
        total: 0,
    };

    //初始化
    ngOnInit() {
        this.getTrees();
    }
    //获取树
    getTrees() {
        this.organizationunitsService.GetTreesAsync().subscribe((data) => {
            this.nodes = data;
        });
    }
    //添加根组织
    createRootUnit() {
        this.modalboxShow(null, null, null);
    }
    //右键菜单展示
    //contextMenu($event: MouseEvent, template: TemplateRef<void>): void {
    //this.dropdown = this.nzDropdownService.create($event, template);
    //}
    contextMenu($event: MouseEvent, menu: NzDropdownMenuComponent): void {
        this.nzContextMenuService.create($event, menu);
    }
    //选择右键菜单下拉
    selectDropdown(type: string): void {
        //this.dropdown.close();
        //this.activedNode选中的节点
        //this.tempNode选中的节点key
        if (type == "sdModifi") {
            this.modalboxShow(this.activedNode.key, null, this.activedNode.title);
        } else if (type == "sdAddSubOrgn") {
            this.modalboxShow(null, this.activedNode.key, null);
        } else if (type == "sdDelete") {
            this.message.confirm(
                "是否确认删除组织单位:'" + this.activedNode.title + "'?",
                '信息确认',
                (result: boolean) => {
                    if (result) {
                        this.organizationunitsService.DeleteOrganizationUnit(Number(this.activedNode.key)).subscribe(() => {
                            this.notify.success('删除成功！');
                            this.getTrees();
                            this.unitUsersList = [];
                            this.queryUser.total = 0;
                        });


                    }
                },
            );
        }
    }
    //显示组织单位模态框
    modalboxShow(_id: any, _parentId: any, _displayName: any) {
        this.modalHelper.open(
            CreateOrUpdateOrganizationUnitsComponent,
            { id: _id, parentId: _parentId, displayName: _displayName },
            'md',
            {
                nzMask: true,
                nzMaskClosable: false
            },
        ).subscribe(isSave => {
            if (isSave) {
                this.getTrees();
            }
        });
    }
    //双击：打开
    openFolder(data: NzTreeNode | NzFormatEmitEvent): void {
        if (data instanceof NzTreeNode) {
            if (!data.isExpanded) {
                data.origin.isLoading = true;
                setTimeout(() => {
                    data.isExpanded = !data.isExpanded;
                    data.origin.isLoading = false;
                }, 500);
            } else {
                data.isExpanded = !data.isExpanded;
            }
        } else {
            // change node's expand status
            if (!data.node.isExpanded) {
                // close to open
                data.node.origin.isLoading = true;
                setTimeout(() => {
                    data.node.isExpanded = !data.node.isExpanded;
                    data.node.origin.isLoading = false;
                }, 500);
            } else {
                data.node.isExpanded = !data.node.isExpanded;
            }
        }
    }
    //单击：选中节点
    activeNode(data: NzFormatEmitEvent): void {
        if (this.activedNode) {
            this.activedNode = null;
        }
        data.node.isSelected = true;
        this.activedNode = data.node;

        this.queryUser.pageIndex = 1;
        this.queryUser.pageSize = 10;
        this.queryRole.pageIndex = 1;
        this.queryRole.pageSize = 10;
        this.tempNode = data.node.key;
        let tempTitle = data.node.title;
        this.cardTitle = "当前节点：" + tempTitle.substring(0, tempTitle.indexOf("（"));
        //触发查询
        this.getUnitUsers(data.node.key);
        this.getUnitRoles(data.node.key);
    }
    //查询组织成员
    getUnitUsers(id: string) {
        this.loading = true;
        let params: any = {};
        params.Id = id;
        params.MaxResultCount = this.queryUser.pageSize;
        params.SkipCount = this.queryUser.skipCount();
        this.organizationunitsService.GetOrganizationUnitUsers(params).subscribe((result: PagedResultDto) => {
            this.unitUsersList = result.items;
            this.queryUser.total = result.totalCount;
        })
    }
    //查询角色
    getUnitRoles(id: string) {
        this.loading = true;
        let params: any = {};
        params.Id = id;
        params.MaxResultCount = this.queryRole.pageSize;
        params.SkipCount = this.queryRole.skipCount();
        this.organizationunitsService.GetOrganizationUnitRoles(params).subscribe((result: PagedResultDto) => {
            this.unitRolesList = result.items;
            this.queryRole.total = result.totalCount;
        })
    }
    //添加组织成员
    addUsers() {
        if (this.tempNode == undefined) {
            this.notify.warn('请选择一个组织单位节点！');
            return;
        }
        this.modalHelper.open(AddUsersComponent, { unitId: this.tempNode }, 'md', { nzMask: true, nzMaskClosable: false }).subscribe(isSave => {
            if (isSave) {
                this.getUnitUsers(this.tempNode);
                this.getTrees();
            }
        });

    }
    //添加角色
    addRoles() {
        if (this.tempNode == undefined) {
            this.notify.warn('请选择一个组织单位节点！');
            return;
        }
        this.modalHelper.open(AddRolesComponent, { unitId: this.tempNode }, 'md', { nzMask: true, nzMaskClosable: false }).subscribe(isSave => {
            if (isSave) {
                this.getUnitRoles(this.tempNode);
            }
        });
    }
    //删除组织成员
    deleteUsers(item) {
        this.message.confirm(
            "是否确认删除组织单位下的用户:'" + item.name + "'?", '删除用户确认',
            (result: boolean) => {
                if (result) {
                    this.organizationunitsService.removeUserFromOrganizationUnit(Number(item.id), Number(this.tempNode)).subscribe(() => {
                        this.notify.success('删除成功！');
                        this.getUnitUsers(this.tempNode);
                        this.getTrees();
                    });


                }
            },
        );
    }
    //删除角色
    deleteRoles(item) {
        this.message.confirm(
            "是否确认删除组织单位下的角色:'" + item.name + "'?", '删除角色确认',
            (result: boolean) => {
                if (result) {
                    this.organizationunitsService.removeRoleFromOrganizationUnit(Number(item.id), Number(this.tempNode)).subscribe(() => {
                        this.notify.success('删除成功！');
                        this.getUnitRoles(this.tempNode);
                    });
                }
            },
        );
    }

}
